/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_manager.htm
 *
 * Zhiqim Manager is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.rule;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.rule.CheckRule;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.annotation.AnGlobal;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.manager.ZmrConstants;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dbo.ZmrDept;
import org.zhiqim.manager.dbo.ZmrOperator;
import org.zhiqim.manager.dbo.ZmrRole;
import org.zhiqim.orm.ORM;

/**
 * 页面验证是否有管理权限，返回boolean =true表示有，=false表示没有
 *
 * @version v1.0.0 @author zouzhigang 2015-5-28 新建与整理
 */
@AnAlias("ZmrManageRule")
@AnGlobal
public class ZmrManageRule implements CheckRule, ZmrConstants
{
    public boolean check(HttpRequest request) throws Exception
    {
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        if (sessionUser == null)
        {// 用户未登录或超时
            return false;
        }

        if (sessionUser.isAdmin())
        {//管理员类型
            return true;
        }
        
        ZmrDept dept = ORM.table().item(ZmrDept.class, ID13);
        ZmrRole role = ORM.table().item(ZmrRole.class, ID13);
        if (hasManageRule(sessionUser.getOperator(), dept, role))
        {//管理权限
            return true;
        }
        
        return false;
    }
    
    /** 判断是否有管理权限 */
    static boolean hasManageRule(ZmrOperator operator, ZmrDept dept, ZmrRole role)
    {
        if (dept != null && dept.isDeptValid())
        {//根部门是否有效
            if (operator.getOperatorCode().equals(dept.getDeptManager()))
            {//根部门负责人
                return true;
            }
            
            if (Validates.isContain(dept.getDeptSubManager(), ",", operator.getOperatorCode()))
            {//根部门副负责人
                return true;
            }
        }
        
        if (role != null && role.isRoleValid())
        {//管理员角色是否有效
            if (Validates.isContain(operator.getOperatorRole(), ",", ""+ID13))
            {//含管理员角色
                return true;
            }
        }
        
        return false;
    }
}